//
//  MJLoginViewController.m
//  MJ
//
//  Created by qiaoBu on 2017/12/11.
//  Copyright © 2017年 lina. All rights reserved.
//

#import "MJLoginViewController.h"
#import "MJLoginView.h"
#import "MJChooseSexController.h"
#import "MJLoginViewModel.h"

@interface MJLoginViewController ()

@property (nonatomic, strong) MJLoginView *loginView;

@end

@implementation MJLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navgationBar.titleLabel.text = @"登录";
    self.view.backgroundColor = RGBColor(242,242,242);
    [self commonInit];
}

- (void)commonInit{
   
    _loginView = [[MJLoginView alloc] initWithFrame:CGRectMake(0, self.navgationBar.height+15, kScreenWidth, kScreenHeight-15-64)];
    [self.view addSubview:_loginView];
    @weakify(self)
    [_loginView setRegisterBlock:^{
        
     @strongify(self)
      
        MJChooseSexController *sexController = [[MJChooseSexController alloc] init];
        [self.navigationController pushViewController:sexController animated:YES];
     }];
    
    [_loginView setRequestVerificationCodeBlcok:^(NSString *telePhone) {
        
         @strongify(self)
        if (self.loginView.telephoneField.text.length)
        {
            [self requestTelephoneCodeWithTelePhone:telePhone];
        }
        else
        {
            [TJMBProgressView showTingJianText:@"请输入手机号"];
        }
    }];
    
    [_loginView setVerificationCodeLoginBlock:^(NSString *telePhone, NSString *verificationCode) {
        
        @strongify(self)
        if (self.loginView.telephoneField.text.length && self.loginView.verifyCodeField.text.length)
        {
            [self loginWithTelePhone:telePhone verificationCode:verificationCode];
        }
        else
        {
            
            [TJMBProgressView showTingJianText:@"请输入手机号和验证码"];
        }
    }];
}
#pragma mark -获取验证码
- (void)requestTelephoneCodeWithTelePhone:(NSString *)telePhone{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:telePhone forKey:@"mobile"];
    [MJLoginViewModel requestCodeWithDict:parameters success:^(NSString *state, NSString *message) {
        
        NSLog(@"%@---%@",state,message);
        if ([state isEqualToString:@"001"])
        {
            [self verificationCodeButtonCountDown];
        }
        else
        {
             [TJMBProgressView showTingJianText:message];
        }
        
    } failure:^(NSError *error) {
       
        NSLog(@"%@",error);
       [TJMBProgressView showTingJianText:networkError];
        
    } netWorkState:^(BOOL netWorkState) {
        
    }];
}
#pragma mark - 登录
- (void)loginWithTelePhone:(NSString *)telePhone verificationCode:(NSString *)verificationCode{
    
    [TJMBProgressView showTingJianTextNeverDismiss:@"登录中" Frame:self.view.bounds toView:self.view];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:telePhone forKey:@"mobile"];
    [parameters setObject:verificationCode forKey:@"code"];

    [MJLoginViewModel requestLoginWithDict:parameters success:^(NSString *state, NSString *message) {
       
        [TJMBProgressView hideHUDForView:self.view];
        NSLog(@"%@---%@",state,message);
        if ([state isEqualToString:@"001"])
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [TJMBProgressView showTingJianText:message];
        }
        
    } failure:^(NSError *error) {
        
        NSLog(@"%@",error);
        [TJMBProgressView hideHUDForView:self.view];
        [TJMBProgressView showTingJianText:networkError];
        
    } netWorkState:^(BOOL netWorkState) {
        
    }];
}
- (void)verificationCodeButtonCountDown{
    
    __block int time = 60;
    __block UIButton *verifybutton = _loginView.verifyCodeBtn;
    verifybutton.userInteractionEnabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time<=0)
        {
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [verifybutton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
                verifybutton.userInteractionEnabled = YES;
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSString *strTime = [NSString stringWithFormat:@"获取验证码(%d)",time];
                [verifybutton setTitle:strTime forState:UIControlStateNormal];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_loginView.telephoneField resignFirstResponder];
    [_loginView.verifyCodeField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
